//
//  ViewController.m
//  AIM
//
//  Created by user10 on 2017/5/15.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "ViewController.h"
#import <AFNetworking.h>
#import "MainViewController.h"
#import "NetWorkTools.h"
#import "MyLog.h"
#import "logViewController.h"
#import "DataBase.h"
#import "logModel.h"

@interface ViewController ()<NSXMLParserDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *LoginBtn;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *IP;
@property (weak, nonatomic) IBOutlet UITextField *IP1;
@property (weak, nonatomic) IBOutlet UITextField *IP2;
@property (weak, nonatomic) IBOutlet UITextField *IP3;
@property (weak, nonatomic) IBOutlet UITextField *IP4;

@end

@implementation ViewController
- (IBAction)userNameL:(id)sender {
}
- (IBAction)passWordL:(id)sender {
}
- (IBAction)LoginBtn:(UIButton *)sender {
#warning "network is not write"
    
    NSUserDefaults *user  = [NSUserDefaults standardUserDefaults];
    [user setObject:_userName.text forKey:@"TANTO_CD"];
    NSString *str = [NSString stringWithFormat:@"%@.%@.%@.%@",_IP1.text,_IP2.text,_IP3.text,_IP4.text];
    [user setObject:str forKey:@"URL"];
    
    [user setObject:_IP1.text forKey:@"IP1"];
    
    [user setObject:_IP2.text forKey:@"IP2"];
    
    [user setObject:_IP3.text forKey:@"IP3"];
    
    [user setObject:_IP4.text forKey:@"IP4"];
    
    //创建log数据库
    [DataBase sharedDataBase];
    
    //soap参数
    NSString *webServiceStr = [NSString stringWithFormat:
                               @"<web:checkLogin>\
                               <arg0>%@</arg0>\
                               <arg1>%@</arg1>\
                               <arg2>%@</arg2>\
                               </web:checkLogin>",COMPANY,_userName.text,_password.text];
    NetWorkTools *tools = [NetWorkTools shareTools];
    
    [tools request:POST urlString:[NSString stringWithFormat:@"http://%@.%@.%@.%@:8888/webservice/ws/LoginImplPort?wsdl",_IP1.text,_IP2.text,_IP3.text,_IP4.text] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *string = result;
        if (result.length != 0) {
            NSRange startRange = [string rangeOfString:@"<return>"];
            NSRange endRange = [string rangeOfString:@"</return>"];
            NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
            if (range.location == NSNotFound) {
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"NetWork error" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
                [alert show];
                
            }else{
                NSString *resultString = [string substringWithRange:range];
                //TANTO_CD标识存入用户偏好设置
                if([resultString isEqualToString:@"FAILED"]){
                    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Account or password is not correct" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
                    [alert show];
                }else{
                    if (0 == _IP1.text.length && 0 == _IP2.text.length && 0 == _IP3.text.length && 0 == _IP4.text.length) {
                        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The IP address cannot be empty" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
                        [alert show];
                    }else{
                        NSRange cdRange = [string rangeOfString:@"S@@"];
                        NSRange cdEndRange = [string rangeOfString:@"@@"];
                        NSRange cdResultRange = NSMakeRange(cdRange.location + cdRange.length, cdEndRange.location - cdRange.location - cdRange.length);
                        if (cdResultRange.location != NSNotFound) {
                            NSString *TANTO_CD = [string substringWithRange:cdResultRange];
                            NSLog(@"%@",TANTO_CD);
                            UIStoryboard *mainStoryboard = self.storyboard;
                            [[MyLog shareMyLog]addWithOperation:@"登录成功" type:@"图片" name:@"aksdjfklajsldf.png"];
                            
                            NSDate *date = [NSDate date]; // 获得时间对象
                            
                            NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
                            
                            [forMatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
                            
                            NSString *dateStr = [forMatter stringFromDate:date];
                            
                            logModel *log = [[logModel alloc]init];
                            log.time = dateStr;
                            log.opration = @"LOGIN success";
                            log.type = @"";
                            log.filename = @"";
                            
                            [[DataBase sharedDataBase]addLogModel:log];
                            
                            MainViewController *push=[mainStoryboard instantiateViewControllerWithIdentifier:@"MainViewController"];
                            [self.navigationController pushViewController:push animated:YES];
                            [user setObject:resultString forKey:@"login"];
                        }else{
                            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"NetWork error" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
                            [alert show];
                        }
                    }
                }
            }
        }else if (result.length == 0){
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"IPアドレスが間違っているためサーバ接続に失敗しました。" delegate:self cancelButtonTitle:@"Ok！" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
    
    _password.text = nil;
    _userName.text = nil;

    [_userName becomeFirstResponder];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _LoginBtn.layer.cornerRadius = 8;
    
    _userName.delegate = self;
    _userName.returnKeyType = UIReturnKeyNext;
    
    _password.delegate = self;
    _password.returnKeyType = UIReturnKeyNext;
    
    _IP.delegate = self;
    _IP.returnKeyType = UIReturnKeyDone;
    
    _IP1.delegate = self;
    _IP1.returnKeyType = UIReturnKeyNext;
    
    _IP2.delegate = self;
    _IP2.returnKeyType = UIReturnKeyNext;
    
    _IP3.delegate = self;
    _IP3.returnKeyType = UIReturnKeyNext;
    
    _IP4.delegate = self;
    _IP4.returnKeyType = UIReturnKeyDone;
    
    _IP1.text = [NSUD objectForKey:@"IP1"];
    _IP2.text = [NSUD objectForKey:@"IP2"];
    _IP3.text = [NSUD objectForKey:@"IP3"];
    _IP4.text = [NSUD objectForKey:@"IP4"];
    
    [_IP1 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_IP2 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_IP3 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_IP4 addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)logBtn:(id)sender {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"bundle:nil];
    logViewController *logVc = [mainStoryboard instantiateViewControllerWithIdentifier:@"LogViewController"];
    [self presentViewController:logVc animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.userName endEditing:YES];
    [self.password endEditing:YES];
    [self.IP1 endEditing:YES];
    [self.IP2 endEditing:YES];
    [self.IP3 endEditing:YES];
    [self.IP4 endEditing:YES];
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.IP1 ) {
        if (textField.text.length > 3) {
            textField.text = [textField.text substringToIndex:3];
        }
    }else if (textField == self.IP2){
        if (textField.text.length > 3) {
            textField.text = [textField.text substringToIndex:3];
        }
    }else if (textField == self.IP3){
        if (textField.text.length > 3) {
            textField.text = [textField.text substringToIndex:3];
        }
    }else if (textField == self.IP4){
        if (textField.text.length > 3) {
            textField.text = [textField.text substringToIndex:3];
        }
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _userName) {
        [_password becomeFirstResponder];
    }else if (textField == _password){
        [_IP1 becomeFirstResponder];
    }else if (textField == _IP1){
        [_IP2 becomeFirstResponder];
    }else if (textField == _IP2){
        [_IP3 becomeFirstResponder];
    }else if (textField == _IP3){
        [_IP4 becomeFirstResponder];
    }
    return YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
